<?php

/**
 * Created by PhpStorm.
 * User: 勇林
 * Date: 2015/12/17
 * Time: 17:17
 */

namespace app\api\controllers;

use app\api\Constant;
use app\common\utils\Util;
use app\models\GkyMsgDocument;
use app\models\GkyMsgReply;
use app\models\GkyMsgUser;
use app\models\GkyQyhUser;
use app\models\GkyUser;
use Faker\Provider\Uuid;
use Overtrue\Wechat\Utils\Arr;
use yii\web\Controller;
use app\api\Response;
use yii\helpers\ArrayHelper;
use app\models\Msg;
use app\models\GkyQyh;
use app\common\utils\QyWechat;

class MessageController extends Controller {

    public function actionAcceptMsgs($userid, $pageNow, $pageSize) {

        $list = GkyMsgUser::findAcceptList($userid, $pageNow, $pageSize);
        Response::setHeader();
        echo json_encode(ArrayHelper::toArray($list));
    }

    public function actionSendMsgs($userid, $pageNow, $pageSize) {

        $list = GkyMsgUser::findSendList($userid, $pageNow, $pageSize);
        Response::setHeader();
        echo json_encode(ArrayHelper::toArray($list));
    }

    public function actionUnreadMsgs($userid, $pageNow, $pageSize) {

        $list = GkyMsgUser::findUnreadList($userid, $pageNow, $pageSize);
        Response::setHeader();
        echo json_encode(ArrayHelper::toArray($list));
    }

    public function actionCollectMsgs($userid, $pageNow, $pageSize) {

        $list = GkyMsgUser::findCollectList($userid, $pageNow, $pageSize);
        Response::setHeader();
        echo json_encode(ArrayHelper::toArray($list));
    }

    /**
     * 获取该消息的详细信息，包括回复的信息
     * @param type $msgid
     * @param type $pageNow
     * @param type $pageSize
     */
    public function actionGetMessageDetail($msgid, $userid) {

        //标记为已读
        $msgUser = GkyMsgUser::findByMsgidAndUserid($msgid, $userid);
        if($msgUser != null){
            $msgUser->isread = 1;
            $msgUser->readtime = time();
            $msgUser->save();
        }

        $message = Msg::findOne($msgid);
        $accepters = GkyMsgUser::findAccepter($msgid);
        if ($message != null) {
            $reply = GkyMsgReply::getReplyList($msgid, 1, 10);
            $document = GkyMsgDocument::getDocumentList($msgid);
            $result = ArrayHelper::toArray($message);
            $result['username'] = $message->qyhUser->name;
            $result['avatar'] = $message->qyhUser->avatar;
            $result['accepters'] = ArrayHelper::toArray($accepters);
            $result['reply'] = $reply;
            $result['document'] = $document;
            if($msgUser != null){
                $result['iscollect'] = $msgUser->iscollect ;
            }else{
                $result['iscollect'] = -2;  //标记为无法收藏
            }
            Response::setHeader();
            echo json_encode(ArrayHelper::toArray($result));
        } else {
            Response::setHeader();
            echo json_encode(array());
        }
    }

    public function actionGetReplyList($msgid, $pageNow, $pageSize){
        $result = GkyMsgReply::getReplyList($msgid, $pageNow, $pageSize);
        Response::setHeader();
        echo json_encode(ArrayHelper::toArray($result));
    }

    /**
     * 创建新消息
     *
     * @param $userid
     */
    public function actionCreateMessage($userid) {
        $data = \Yii::$app->request->post();

        //下载图片并保存
        $images = isset($data['images']) ? $data['images'] : array();
        $options = array(
            'token'=>'gky',   //填写应用接口的Token
            'encodingaeskey'=>Constant::$GKY_AESKEY,//填写加密用的EncodingAESKey
            'appid'=>Constant::$GKY_CORPID,  //填写高级调用功能的appid
            'appsecret'=>Constant::$GKY_SECRET, //填写高级调用功能的密钥
        );
        $filepaths = [];
        foreach($images as $image){
            $weObj = new QyWechat($options);
            $img = $weObj->getMedia($image);
            $imageName = Util::guid().'.jpg';
            file_put_contents(\Yii::$app->basePath.'/web/uploads/images/'.$imageName,$img);
            $filepaths[] = Constant::$BASE_FILE_URL.$imageName;
        }

        $msg = new Msg();
        $msg->msgtype = isset($data['msgtype']) ? $data['msgtype'] : 'OA办文';
        $msg->addmanid = $userid;
        $msg->isforward = isset($data['isforward']) ? $data['isforward'] : 0;
        $msg->forwardid = isset($data['forwardid']) ? $data['forwardid'] : 0;
        $msg->content = isset($data['content']) ? $data['content'] : '';
        $msg->description = isset($data['description']) ? $data['description'] : '';
        $msg->title = isset($data['title']) ? $data['title'] : '';
        $msg->meetingtime_start = isset($data['meetingtime_start']) ? $data['meetingtime_start'] : '';
        $msg->meetingtime_end = isset($data['meetingtime_end']) ? $data['meetingtime_end'] : '';
        $msg->meetingplace = isset($data['meetingplace']) ? $data['meetingplace'] : '';
        $result = [];

        if($msg->save()){

            $msg = Msg::find()->where(['title'=>$msg->title])->orderBy(['id'=>SORT_DESC])->one();
            $accepters = isset($data['accepters']) ? $data['accepters'] : [];
            for($i = 0; $i < count($accepters);$i++){
                $msgUser = new GkyMsgUser();
                $msgUser->msgid = $msg->id;
                $msgUser->userid = $accepters[$i];
                $msgUser->save();
            }

            //保存图片路径
            GkyMsgDocument::saveList($msg->id, $filepaths);

            $result['status'] = 0;

            $this->sendMessage($accepters,$msg);
        }else{
            $result['status'] = -1;
        }

        Response::setHeader();
        echo json_encode($result);

    }

    public function sendMessage($accepters,$msg){

        $touser = GkyQyhUser::findUseridByList($accepters,Constant::$GKY_CORPID);
        $touser = implode("|",$touser);
        if($msg->msgtype == 'OA办文'){
            $picUrl = \Yii::$app->request->hostInfo.'/GkyWechat/images/oa.png';
        }else{
            $picUrl = \Yii::$app->request->hostInfo.'/GkyWechat/images/meeting.jpg';
        }

        $message = [
            "touser" => $touser,
//            "toparty" => "PartyID1|PartyID2 ",
//            "totag" => "TagID1|TagID2 ",
            "safe"=> "0",			//是否为保密消息，对于news无效
            "agentid" => "1",	//应用id
            "msgtype" => "news",  //根据信息类型，选择下面对应的信息结构体

            "news" => array(			//不支持保密
                  "articles" => array(    //articles  图文消息，一个图文消息支持1到10个图文
                      array(
                          "title" => $msg->title,             //标题
                          "description" => $msg->description, //描述
                          "url" => "http://gky.fukangyun.com/GkyWechat/message/content.html?msgid=".$msg->id,                 //点击后跳转的链接。可根据url里面带的code参数校验员工的真实身份。
                          "picurl" => $picUrl,          //图文消息的图片链接,支持JPG、PNG格式，较好的效果为大图640*320，
                                                          //小图80*80。如不填，在客户端不显示图片
                      ),
                  )
              ),
        ];

        $this->send($message);

    }

    /**
     * 发送回复消息
     *
     * @param $reply
     */
    public function sendReply($reply){

//        $user = GkyQyhUser::findOne($reply->msg->qyhUser);
        $msg = Msg::findOne($reply->msgid);

//        \Yii::info('touser:'.$user->userid,'weixin');

        $message = [
            "touser" => $msg->qyhUser->userid.'',
//            "toparty" => "PartyID1|PartyID2 ",
//            "totag" => "TagID1|TagID2 ",
            "safe"=> "0",			//是否为保密消息，对于news无效
            "agentid" => "1",	//应用id
            "msgtype" => "text",  //根据信息类型，选择下面对应的信息结构体

            "text" => array(
                  "content" => $reply->qyhUser->name.' 回复了您的【'.$msg->title.'】消息:'.$reply->reply
            ),
        ];

        $this->send($message);
    }

    public function send($message){
        //获取当前企业号
        $weaccount = GkyQyh::findByCorpid(Constant::$GKY_CORPID);

        $options = array(
            'token'=>'gky',   //填写应用接口的Token
            'encodingaeskey'=>$weaccount->aeskey,//填写加密用的EncodingAESKey
            'appid'=>$weaccount->corpid,  //填写高级调用功能的appid
            'appsecret'=>$weaccount->secret, //填写高级调用功能的密钥
        );
        $weObj = new QyWechat($options);
        $weObj->sendMessage($message);


    }

    /**
     * 回复消息
     */
    public function actionReply(){

        $data = \Yii::$app->request->get();
        $reply = new GkyMsgReply();
        $reply->msgid = $data['msgid'];
        $reply->userid = $data['userid'];
        $reply->reply = $data['reply'];
        $result = [];
        if($reply->save()){
            $result['status'] = 0;
            $this->sendReply($reply);
        }else {
            $result['status'] = -1;
        }
        Response::setHeader();
        echo json_encode($result);
    }

    public function actionCollect($msgid, $userid){
        $msgUser = GkyMsgUser::findByMsgidAndUserid($msgid, $userid);
        if($msgUser != null){
            $msgUser->iscollect = 1;
            Response::setHeader();
            if($msgUser->save()){
                echo json_encode(['status'=>0]);
            }else{
                echo json_encode(['status'=>-1]);
            }
        }else{
            echo json_encode(['status'=>-1]);
        }

    }
    public function actionSendSearch($userid,$str){
        $list = GkyMsgUser::searchBySend($userid, $str);
         Response::setHeader();
        return json_encode(ArrayHelper::toArray($list));
    }

    public function actionAcceptSearch($userid,$str){
        $list = GkyMsgUser::find()
            ->where(['userid'=>$userid])
            ->all();
        $results = [];
        foreach($list as $model){
            $results[] = $model->msgid;
        }
        
        $messages = Msg::find()
            ->where(['and',['in','id',$results],['or',['like','title',$str],['like','description',$str],['like','content',$str],['like','msgtype',$str]]])
            ->all();
           Response::setHeader();
        return json_encode(ArrayHelper::toArray($messages));

    }

}
